package com.example.concurrency.threadpool.futuretask;

import com.example.concurrency.threadpool.MyThreadPoolExecutor;

import java.util.concurrent.*;

/**
 * @author ZhenWuWang
 */
public class FutureTaskDemo
{

    private ExecutorService threadPool = new MyThreadPoolExecutor(5, 10, 1,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(5),
            new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args)
    {
        FutureTaskDemo futureTaskDemo = new FutureTaskDemo();
        futureTaskDemo.testSubmit();
    }

    public void testSubmit()
    {
        System.out.println("start");
        for (int i = 0; i < 5; i++)
        {
            FutureTask<Integer> futureTask = new FutureTask<>(new MyCallable(i));
            try
            {
                threadPool.submit(futureTask).get();
            } catch (InterruptedException | ExecutionException e)
            {
                e.printStackTrace();
            }
        }
        System.out.println("end");
    }

    private static class MyCallable implements Callable<Integer>
    {
        private final Integer num;

        private String name;

        private MyCallable(Integer num)
        {
            this.num = num;
            this.name = "线程" + num;
        }

        @Override
        public Integer call() throws Exception
        {
            int i = 0;
            for (; i <= num; i++)
            {
                System.out.println(name + ": " + i);
                try
                {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
            return i;
        }
    }
}
